package ug.co.icom.kyazze.healthticket.data;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class QueryBuilder {

	Locale locale = Locale.getDefault();
	private String comma = "%2C";
	public String getDatabaseName() {
		return "mHealth";
	}

	public String getApiKey() {
		return "8qvfwj4yp5q8ikntgvta";
	}
	
	public String getBaseUrl()
	{
		return "https://api.mongohq.com/databases/"+getDatabaseName()+"/collections/";
	}
	
	public String docApiKeyUrl()
	{
		return "/documents?_apikey="+getApiKey();
	}
	
	public String docApiKeyUrl(String docid)
	{
		return "/documents/"+docid+"?_apikey="+getApiKey();
	}
	
	public String buildPersonalDetailsUpdate(String docid)
	{
		return getBaseUrl()+personalRec()+docApiKeyUrl(docid);
	}

	
	public String queryUrl()
	{
		return "&q=";
	}
	
	public String medicalRec()
	{
		return "medical_records";
	}
	
	public String personalRec()
	{
		return "personal_details";
	}
	
	public String appRec()
	{
		return "app_data";
	}
	

	public String addComma(String first, String second)
	{
		return first +"%2C"+second;
	}
	
	public String provideValue(String name, String value)
	{
		return "%22"+name+"%22:%22"+value+"%22";
	}
	
	public String provideLikeValue(String name, String value)
	{
		return "%22"+name+"%22:%2F.*"+value+".*%2F";
	}
	
	public String addBraces(String value)
	{
		return "%7B"+value+"%7D";
	}

	public String getPersonalCol() {
		return "personal_details";
	}	
	
	public String addFieldQuery()
	{
		return "&fields=";
	}
	
	public String buildPersonalDetailsQuery()
	{
		return getBaseUrl()+personalRec()+docApiKeyUrl()+queryUrl();
	}
	
	public String buildMedicalRecordsQuery()
	{
		return getBaseUrl()+medicalRec()+docApiKeyUrl()+queryUrl();
	}
	
	public String buildAppDataQuery()
	{
		return getBaseUrl()+appRec()+docApiKeyUrl();
	}
	
	public String buildPersonalDetailsCreate()
	{
		return getBaseUrl()+personalRec()+docApiKeyUrl();
	}
	
	public String createUser(User user)
	{
		return String
		.format("{\"document\"  : {\"phonenumber\": \"%s\", "
				+ "\"passcode\": \"%s\", \"firstname\": \"%s\", "
				+ "\"lastname\": \"%s\", \"othernames\": \"%s\", "
				+ "\"address\": \"%s\", \"bloodtype\": \"%s\", "
				+ "\"female\": %s, \"dateofbirth\": \"%s\","
				+ "\"email\": \"%s\","
				+ "\"medical_id\": \"%s\"}, \"safe\" : true}",
				user.PhoneNumber, user.PassCode, user.FirstName, user.LastName,
				user.OtherNames, user.Address, user.BloodType, user.Female.toString(),
				getStringFromDate(user.DateOfBirth), user.Email, user.Medical_id);
	}
	
	
	public String createMedicalDoc()
	{
		return String
		.format("{\"document\"  : {\"allergies\": \"[]\", "
				+ "\"conditions\": \"[]\", \"imaging\": \"[]\", "
				+ "\"immunizations\": \"[]\", \"lab\": \"[]\", "
				+ "\"medications\": \"[]\", \"surgery\": \"[]\"}, \"safe\" : true}");
	}

	private String getStringFromDate(Date dateReceived) {
		SimpleDateFormat  dateFormat = new SimpleDateFormat("dd-MM-yyyy", locale);  
		try {  
		    String date = dateFormat.format(dateReceived);  
		    return date;  
		} catch (Exception e) {  
		    return "";
		}
	}
	
	public String buildLoginUrl(String userName, String password)
	{
		String toReturn = buildPersonalDetailsQuery()+
				addBraces(							
						addComma(
								provideValue("phonenumber", userName),
								provideValue("passcode", password)
								)
						);
		return toReturn;
	}
	
	public String buildEmailUrl(String email)
	{
		String toReturn =buildPersonalDetailsQuery()+
				addBraces(							
						provideValue("email", email)
						);
		
		return toReturn;
	}
	
	public String buildMedicalObjectUrl(String randomtag)
	{
		String toReturn =buildMedicalRecordsQuery()+
				addBraces(							
						provideValue("random_tag", randomtag)
						);
		
		return toReturn;
	}
	
	
	public String buildSearchConnectionUrl(String query)
	{
String toReturn = buildPersonalDetailsQuery();
		
		String[] names = query.split(" ");
		
		String namesToSend = "";
		int i = 1;
		for(String name:names)
		{
			namesToSend += addBraces(provideLikeValue("firstname", name));
			namesToSend += comma;
			namesToSend += addBraces(provideLikeValue("lastname", name));
			namesToSend += comma;
			namesToSend += addBraces(provideLikeValue("othernames", name));
			if(i<names.length)
			{
				namesToSend += comma;
			}
			i++;
		}
		
		toReturn += addBraces("$or:["+namesToSend+"]");
		
		return toReturn;
	}
	
	/**
	 * 
	 * @param user
	 * @param permissions
	 * @return
	 */
	public String getRequestConnDetails(MinUser user, Permissions permissions) {
		return String.format("{\"document\" : { \"$addToSet\" : " // findAndModify set set_and_addToSet
				+ "{\"connrequests\" : {\"uid\" : \"%s\" , "
				+ "\"firstname\" : \"%s\", "
				+ "\"lastname\" : \"%s\", "
				+ "\"othernames\" : \"%s\", "
				+ "\"phonenumber\" : \"%s\", "
				+ "\"dateofbirth\" : \"%s\", "
				+ "\"allergies\" : \"%s\", "
				+ "\"medication\" : \"%s\", "
				+ "\"immunization\" : \"%s\", "
				+ "\"labdata\" : \"%s\", "
				+ "\"conditions\" : \"%s\", "
				+ "\"imaging\" : \"%s\", "
				+ "\"insurance\" : \"%s\", "
				+ "\"surgeries\" : \"%s\","
				+ "\"reviewed\" : \"false\" }"
				+ "} "
				+ "}, \"safe\" : true}",
				user.ID, user.FirstName, user.LastName, user.OtherNames,
				permissions.PhoneNumber, permissions.DateOfBirth,
				permissions.Allergies, permissions.Medication,
				permissions.Immunization, permissions.LabData,
				permissions.Conditions, permissions.Imaging,
				permissions.Insurance, permissions.Surgeries);
	}
	
	/**
	 * The PHR owner gets to review the request and either accept or reject it
	 * @param user
	 * @param permissions
	 * @return
	 */
	public String reviewRequestConnDetails(MinUser user, Permissions permissions) {
		return String.format("{\"document\" : { \"$set\" : " // findAndModify 
				+ "{\"connrequests\" : {\"uid\" : \"%s\" , "
				+ "\"firstname\" : \"%s\", "
				+ "\"lastname\" : \"%s\", "
				+ "\"othernames\" : \"%s\", "
				+ "\"phonenumber\" : \"%s\", "
				+ "\"dateofbirth\" : \"%s\", "
				+ "\"allergies\" : \"%s\", "
				+ "\"medication\" : \"%s\", "
				+ "\"immunization\" : \"%s\", "
				+ "\"labdata\" : \"%s\", "
				+ "\"conditions\" : \"%s\", "
				+ "\"imaging\" : \"%s\", "
				+ "\"insurance\" : \"%s\", "
				+ "\"surgeries\" : \"%s\" }"
				+ "} "
				+ "}, \"safe\" : true}",
				user.ID, user.FirstName, user.LastName, user.OtherNames,
				permissions.PhoneNumber, permissions.DateOfBirth,
				permissions.Allergies, permissions.Medication,
				permissions.Immunization, permissions.LabData,
				permissions.Conditions, permissions.Imaging,
				permissions.Insurance, permissions.Surgeries);
	}
	
	
	
	public String buildMedicalObjectUrlPutURL(String doc_id)
	{
		String val = getBaseUrl()+medicalRec()+docApiKeyUrl(doc_id);
		
		@SuppressWarnings("unused")
		String toReturn =buildMedicalRecordsQuery()+
				addBraces(							
						provideValue("_id", doc_id)
						);
		
		return val;
	}
	
	public String buildGetConnectionRequestsUrl(String phoneNumber) {
		String toReturn = buildPersonalDetailsQuery()+
				addBraces(							
						provideValue("phonenumber", phoneNumber)
						)
						+
				addFieldQuery()+
				addBraces(provideValue("connrequests", "true"));
		return toReturn; 
	}
	
}
